package object

import (
	"encoding/json"
	"time"

	"bmember/pkg/util"

	pay_rpc "bmember/api/pb/client/pay/api/pay"
	"bmember/internal/model"
)

const (
	// 初始状态，待支付（支付单状态）
	PayOrderStatus_PAY_ORDER_STATUS_INIT int8 = 0
	// 支付中（前端已确定支付成功 / 已提交会员支付）（支付单状态）
	PayOrderStatus_PAY_ORDER_STATUS_PAYING int8 = 1
	// 支付成功（支付单状态）
	PayOrderStatus_PAY_ORDER_STATUS_SUCCESS int8 = 2
	// 支付失败（支付单状态）
	PayOrderStatus_PAY_ORDER_STATUS_FAILED int8 = 3
	// 支付关闭（支付单状态）
	PayOrderStatus_PAY_ORDER_STATUS_CLOSED int8 = 4
	// 待提交退款（退款单状态）
	PayOrderStatus_REFUND_ORDER_STATUS_INIT int8 = 10
	// 退款中(第三方返回退款已提交等)（退款单状态）
	PayOrderStatus_REFUND_ORDER_STATUS_REFUNDING int8 = 11
	// 退款成功（退款单状态）
	PayOrderStatus_REFUND_ORDER_STATUS_SUCCESS int8 = 12
	// 退款协商成功（退款单状态）
	PayOrderStatus_REFUND_ORDER_STATUS_MARKED_SUCCESS int8 = 13
	// 退款失败（退款单状态）
	PayOrderStatus_REFUND_ORDER_STATUS_FAILED int8 = 14
)

// WechatPrepayInfo 微信预支付单
type WechatPrepayInfo struct {
	// 应用id
	AppId string `json:"app_id"`
	// 随机字符串
	NonceStr string `json:"nonceStr"`
	// 订单详情扩展字符串，统一下单接口返回的prepay_id参数值，提交格式如：prepay_id=***
	Package string `json:"package"`
	// 签名方式
	SignType string `json:"signType"`
	// 时间戳（秒）
	TimeStamp string `json:"timestamp"`
	// 签名
	PaySign string `json:"paySign"`
}

// PlatformPrepay 预支付信息
type PlatformPrepay struct {
	// 支付单号
	PayOrderNo string `json:"pay_order_no"`
	// 预支付单提交信息(微信为固有格式，支付宝为{"trade_no": ""...}，字节为固有格式)
	PrepayInfo []byte `json:"prepay_info"`
	// 支付方式名称
	PayTypeName string `json:"pay_type_name"`
}

// CreatePayOrderInfo 创建支付请求信息
type CreatePayOrderInfo struct {
	// 支付者唯一标识（通常可取会员ID），用于限制并发和生成订单号
	OrderKey string `json:"order_key"`
	// 品牌ID
	BrandId int64 `json:"brand_id"`
	// 小程序app_id
	AppId string `json:"app_id"`
	// 小程序open_id
	OpenId string `json:"open_id"`
	// 订单来源应用
	BilinApp int8 `json:"order_source"`
	// 总部~0/店铺ID
	StoreId int64 `json:"store_id"`
	// 支付业务唯一请求号，可以使用uuid
	BizNo string `json:"biz_no"`
	// 支付金额（单位：分），允许0分订单创建
	Amount uint64 `json:"amount"`
	// 透传大字段(外围指定，不感知)
	Remark []byte `json:"remark"`
	// 服务商app_id（小程序插件支付场景必须），非插件模式取token的app_id
	IsvAppId string `json:"isv_app_id"`
	// 服务商open_id（小程序插件支付场景必须），非插件模式取token的open_id
	IsvOpenId string `json:"isv_open_id"`
	// 卡信息
	CardInfo *CardInfo `json:"card_info"`
}

// SetBilinApp 设置下单应用
func (c *CreatePayOrderInfo) SetBilinApp(ch string) error {
	switch ch {
	case model.ChannelMallMinaStr:
		c.BilinApp = model.ChannelMallMINA
	case model.ChannelBgMinaStr:
		c.BilinApp = model.ChannelBgMINA
	case model.ChannelMallByteStr:
		c.BilinApp = model.ChannelMallByte
	case model.ChannelMallAlipayStr:
		c.BilinApp = model.ChannelMallAlipay
	default:
		return model.InvalidOrderSorceType
	}
	return nil
}

type CardInfo struct {
	// 品牌id
	BrandId int64 `json:"brand_id"`
	// 会员id
	MemberId int64 `json:"member_id"`
	// 卡id
	CardId int64 `json:"card_id"`
	// 账号id
	AccId int64 `json:"acc_id"`
}

// ToJson json 格式化
func (c *CardInfo) ToJson() []byte {
	b, _ := json.Marshal(c)
	return b
}

// PayOrderDetail 支付单详情
type PayOrderDetail struct {
	// 品牌id
	BrandId int64 `json:"brand_id"`
	// 门店id
	StoreId int64 `json:"store_id"`
	// 支付单号
	PayOrderNo string `json:"order_number"`
	// 支付单状态
	Status int8 `json:"status"`
	// 原始支付金额
	OriginAmount uint64 `json:"origin_amount"`
	// 商户优惠金额
	MerchantDiscount uint64 `json:"merchant_discount"`
	// 平台优惠金额
	PlatformDiscount uint64 `json:"platform_discount"`
	// 用户实付金额
	UserPayed uint64 `json:"user_payed"`
	// 商家实收金额
	MerchantReceived uint64 `json:"merchant_received"`
	// 累计退款金额
	RefundedAmount int64 `json:"refunded_amount"`
	// 支付方式名称
	PayTypeName string `json:"pay_type_name"`
	// 支付时间(YYYY-mm-dd HH:MM:SS)
	PayTime time.Time `json:"pay_time"`
	// 透传大字段(外围指定，不感知)
	Remark []byte `json:"remark"`
	// 外部订单号
	BizNo string `json:"biz_no"`
	// 用户身份标识
	OrderKey string `json:"order_key"`
	// 卡信息
	CardInfo []byte `json:"card_info"`
}

// PayOrderViewPayToOrderDetail 比邻支付订单详情与本地订单详情转换
func PayOrderViewPayToOrderDetail(detail *pay_rpc.PayOrderView) *PayOrderDetail {
	if detail == nil {
		return nil
	}
	payTime, _ := util.StdTimeParse(detail.PayTime)
	return &PayOrderDetail{
		BrandId:          int64(detail.SgId),
		StoreId:          int64(detail.StoreId),
		PayOrderNo:       detail.OrderNumber,
		Status:           int8(detail.Status),
		OriginAmount:     detail.OriginAmount,
		MerchantDiscount: detail.MerchantDiscount,
		PlatformDiscount: detail.PlatformDiscount,
		UserPayed:        detail.UserPayed,
		MerchantReceived: detail.Receive,
		RefundedAmount:   detail.RefundedAmount,
		PayTypeName:      detail.PayTypeName,
		PayTime:          payTime,
		Remark:           detail.Remark,
		BizNo:            detail.BizNo,
		OrderKey:         detail.OrderKey,
		CardInfo:         detail.CardInfo,
	}
}

// IsPaySuccess 实付成功
func (p *PayOrderDetail) IsPaySuccess() bool {
	return p.Status == PayOrderStatus_PAY_ORDER_STATUS_SUCCESS
}

// IsFinalStatus 是否是终态
func (p *PayOrderDetail) IsFinalStatus() bool {
	switch p.Status {
	case PayOrderStatus_PAY_ORDER_STATUS_INIT, PayOrderStatus_PAY_ORDER_STATUS_PAYING:
		return false
	default:
		return true
	}
}

// GetCardInfo 获取卡信息
func (p *PayOrderDetail) GetCardInfo() *CardInfo {
	ret := &CardInfo{}
	if p.CardInfo != nil {
		_ = json.Unmarshal(p.CardInfo, ret)
	}
	return ret
}

// ToRechargeOrderStatus 将支付单状态映射为充值单状态
func (p *PayOrderDetail) ToRechargeOrderStatus() int8 {
	switch p.Status {
	case PayOrderStatus_PAY_ORDER_STATUS_INIT:
		return model.RechargeOrderUnpayed
	case PayOrderStatus_PAY_ORDER_STATUS_PAYING:
		return model.RechargeOrderPaying
	case PayOrderStatus_PAY_ORDER_STATUS_SUCCESS:
		return model.RechargeOrderPayed
	case PayOrderStatus_PAY_ORDER_STATUS_FAILED:
		return model.RechargeOrderPayFailed
	case PayOrderStatus_PAY_ORDER_STATUS_CLOSED:
		return model.RechargeOrderClosed
	case PayOrderStatus_REFUND_ORDER_STATUS_INIT:
		return model.RechargeOrderRefunding
	case PayOrderStatus_REFUND_ORDER_STATUS_REFUNDING:
		return model.RechargeOrderRefunding
	case PayOrderStatus_REFUND_ORDER_STATUS_SUCCESS:
		return model.RechargeOrderRefunded
	case PayOrderStatus_REFUND_ORDER_STATUS_MARKED_SUCCESS:
		return model.RechargeOrderRefunded
	case PayOrderStatus_REFUND_ORDER_STATUS_FAILED:
		return model.RechargeOrderRefundFailed
	default:
		return 0
	}
}

// CreateRefundOrderInfo 退款申请详情
type CreateRefundOrderInfo struct {
	// 支付单号
	PayOrderNo string `json:"pay_order_no"`
	// 员工id
	EmpId int64 `json:"emp_id"`
	// 退款金额
	RefundAmount uint64 `json:"refund_amount"`
	// 请求唯一标识（订单号）
	BizNo string `json:"biz_no"`
	// 退款原因
	Reason string `json:"reason"`
}

// RefundOrderDetail 退款订单详情
type RefundOrderDetail struct {
	// 品牌id
	BrandId int64 `json:"brand_id"`
	// 门店id
	StoreId int64 `json:"store_id"`
	// 退款单号
	RefundOrderNo string `json:"refund_order_no"`
	// 退款单状态
	Status int8 `json:"status"`
	// 退还支付金额（单位：分）
	OriginAmount uint64 `json:"origin_amount"`
	// 退还商家优惠金额
	MerchantDiscount uint64 `json:"merchant_discount"`
	// 退还平台优惠金额
	PlatformDiscount uint64 `json:"platform_discount"`
	// 用户退款到账金额
	UserReceived uint64 `json:"user_received"`
	// 商家退款实际扣款金额
	MerchantPayed uint64 `json:"merchant_payed"`
	// 退款方式名称
	PayTypeName string `json:"pay_type_name"`
	// 退款时间(YYYY-mm-dd HH:MM:SS)
	PayTime time.Time `json:"pay_time"`
	// 支付透传大字段(外围指定，不感知)
	Remark []byte `json:"remark"`
	// 退款原因
	Reason string `json:"reason"`
	// 外部订单号
	BizNo string `json:"biz_no"`
	// 原支付单号
	PayOrderNo string `json:"pay_order_no"`
	// 用户身份标识
	OrderKey string `json:"order_key"`
	// 卡信息
	CardInfo []byte `json:"card_info"`
}

// PayOrderViewPayToOrderDetail 比邻退款订单详情与退款订单详情转换
func RefundOrderViewToRefundOrderDetail(detail *pay_rpc.RefundOrderView) *RefundOrderDetail {
	if detail == nil {
		return nil
	}
	payTime, _ := util.StdTimeParse(detail.PayTime)
	return &RefundOrderDetail{
		BrandId:          int64(detail.SgId),
		StoreId:          int64(detail.StoreId),
		RefundOrderNo:    detail.OrderNumber,
		Status:           int8(detail.Status),
		OriginAmount:     detail.OriginAmount,
		MerchantDiscount: detail.MerchantDiscount,
		PlatformDiscount: detail.PlatformDiscount,
		UserReceived:     detail.UserPayed,
		MerchantPayed:    detail.Receive,
		PayTypeName:      detail.PayTypeName,
		PayTime:          payTime,
		Remark:           detail.Remark,
		Reason:           detail.Reason,
		BizNo:            detail.BizNo,
		PayOrderNo:       detail.PayOrderNumber,
		OrderKey:         detail.OrderKey,
		CardInfo:         detail.CardInfo,
	}
}

// IsRefundSuccess 退款成功
func (r *RefundOrderDetail) IsRefundSuccess() bool {
	return r.Status == PayOrderStatus_REFUND_ORDER_STATUS_SUCCESS
}

// IsFinalStatus 是否是终态
func (r *RefundOrderDetail) IsFinalStatus() bool {
	switch r.Status {
	case PayOrderStatus_REFUND_ORDER_STATUS_INIT, PayOrderStatus_REFUND_ORDER_STATUS_REFUNDING:
		return false
	default:
		return true
	}
}

// GetCardInfo 获取卡信息
func (r *RefundOrderDetail) GetCardInfo() *CardInfo {
	ret := &CardInfo{}
	if r.CardInfo != nil {
		_ = json.Unmarshal(r.CardInfo, ret)
	}
	return ret
}

// ToRechargeOrderStatus 将支付单状态映射为充值单状态
func (r *RefundOrderDetail) ToRechargeOrderStatus() int8 {
	switch r.Status {
	case PayOrderStatus_REFUND_ORDER_STATUS_INIT:
		return model.RechargeOrderRefunding
	case PayOrderStatus_REFUND_ORDER_STATUS_REFUNDING:
		return model.RechargeOrderRefunding
	case PayOrderStatus_REFUND_ORDER_STATUS_SUCCESS:
		return model.RechargeOrderRefunded
	case PayOrderStatus_REFUND_ORDER_STATUS_MARKED_SUCCESS:
		return model.RechargeOrderRefunded
	case PayOrderStatus_REFUND_ORDER_STATUS_FAILED:
		return model.RechargeOrderRefundFailed
	default:
		return 0
	}
}
